package com.ugoodtech.mdcc.web.controller;

import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.domain.UserProfile;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.utils.BaseUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.UserProfileResponse;
import com.ugoodtech.mdcc.web.service.OutSideUserService;
import com.ugoodtech.mdcc.web.service.UserProfileService;
import com.ugoodtech.mdcc.web.service.UserService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright © 2013 All Rights Reserved, Ugood Technology, Inc.
 */
@Api(description = "外勤人员接口")
@Controller
@RequestMapping("/outsideUser")
public class OutsideUserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(OutsideUserController.class);
    @Autowired
    UserRepository outsideUserRepository;
    @Autowired
    UserService outsideUserService;

    @Autowired
    FeedbackRepository feedbackRepository;

    @Autowired
    UserProfileService userProfileService;

    @Autowired
    UserProfileRepository userProfileRepository;

    @Autowired
    DepartmentRepository departmentRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private OutSideUserService outSideUserService;

    @Autowired
    private StationRepository stationRepository;


    @ApiOperation("人员列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = UserProfileResponse.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getAllDepartment(@ApiParam("类型") @RequestParam(value = "userType", required = false) String userType,
                                         @ApiParam("员工编号") @RequestParam(value = "code", required = false) String code,
                                         @ApiParam("姓名") @RequestParam(value = "name", required = false) String name,
                                         @ApiParam("手机号码") @RequestParam(value = "telephone", required = false) String telephone,
                                         @ApiParam("关联部门") @RequestParam(value = "departmentIds", required = false) Long departmentIds,
                                         Pageable pageable) {
        isUserLogin();
        Page<UserProfile> userProfile = userProfileService.querySystemUser(userType, code, name, telephone, departmentIds, pageable);
        return JsonResponse.successResponseWithPageData(BaseUtil.getDtoPage(userProfile, pageable, UserProfileResponse.class));
    }

    @ApiOperation("添加人员")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = UserProfileResponse.class)
    })
    @RequestMapping(value = "/addSystemUser", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse addSystemUser(
            @ApiParam(value = "类型 dealers (\"经销商\") insiders (\"内部人员\")", required = true) @RequestParam("userType") String userType,
            @ApiParam(value = "员工编号", required = true) @RequestParam(value = "serialNumber") String serialNumber,
            @ApiParam(value = "姓名") @RequestParam(value = "name") String name,
            @ApiParam(value = "手机号码") @RequestParam(value = "telephone") String telephone,
            @ApiParam(value = "所属部门ID") @RequestParam(value = "departmentIds") String departmentIds,
            @ApiParam(value = "负责省份") @RequestParam(value = "proinces", required = false) String proinces,
            @ApiParam(value = "负责的省份品牌") @RequestParam(value = "proincesAndBrands", required = false) String proincesAndBrands,
            @ApiParam(value = "维修站ID") @RequestParam(value = "stationIds", required = false) String stationIds,
            @ApiParam(value = "功能权限") @RequestParam(value = "authorities", required = false) String authorities,
            @ApiParam(value = "负责的品牌") @RequestParam(value = "brands", required = false) String brands,
            @ApiParam(value = "是否为管理员") @RequestParam(value = "isAdmin", required = false) Boolean isAdmin) {
        isUserLogin();
        JsonResponse jsonResponse = outSideUserService.addSystemUser(userType, serialNumber, name, telephone, departmentIds, proinces, proincesAndBrands, stationIds, authorities, brands, isAdmin);
        if (jsonResponse.isSuccess()) {
            Map<String, Object> data = new HashMap<>();
            data.put("str", name);
            userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_add, LogConstants.business_type_system_user, null, data);
        }
        return jsonResponse;
    }

    @ApiOperation("编辑人员")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = UserProfileResponse.class)
    })
    @RequestMapping(value = "/editSystemUser", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse editSystemUser(
            @ApiParam(value = "用户Id") @RequestParam(value = "userProfileId") Long userProfileId,
            @ApiParam(value = "类型 dealers (\"经销商\") insiders (\"内部人员\")", required = true) @RequestParam("userType") String userType,
            @ApiParam(value = "员工编号", required = true) @RequestParam(value = "serialNumber") String serialNumber,
            @ApiParam(value = "姓名") @RequestParam(value = "name") String name,
            @ApiParam(value = "手机号码") @RequestParam(value = "telephone") String telephone,
            @ApiParam(value = "所属部门ID") @RequestParam(value = "departmentIds") String departmentIds,
            @ApiParam(value = "负责省份") @RequestParam(value = "proinces", required = false) String proinces,
            @ApiParam(value = "负责的省份品牌") @RequestParam(value = "proincesAndBrands", required = false) String proincesAndBrands,
            @ApiParam(value = "维修站ID") @RequestParam(value = "stationIds", required = false) String stationIds,
            @ApiParam(value = "功能权限") @RequestParam(value = "authorities", required = false) String authorities,
            @ApiParam(value = "负责的品牌") @RequestParam(value = "brands", required = false) String brands,
            @ApiParam(value = "是否为管理员") @RequestParam(value = "isAdmin", required = false) Boolean isAdmin) {
        isUserLogin();
        JsonResponse jsonResponse = outSideUserService.editSystemUser(userProfileId, userType, serialNumber, name, telephone, departmentIds, proinces, proincesAndBrands, stationIds, authorities, brands, isAdmin, this.getCurrentUser());
        if (jsonResponse.isSuccess()) {
        }
        return jsonResponse;
    }


    @ApiOperation("激活/禁用系统用户")
    @RequestMapping(value = "/enableUser", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse enableUser(@ApiParam(value = "用户数据库id", required = true) @RequestParam(value = "outsideUserId") Long outsideUserId,
                                   @ApiParam(value = "激活/禁用", required = true) @RequestParam(value = "enabled") boolean enabled) {
        isUserLogin();
        UserProfile outsideUser = userProfileRepository.findOne(outsideUserId);
        if (outsideUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此系统用户");
        }
        if (outsideUser.isEnabled() == false && enabled == false) {
            return JsonResponse.errorResponseWithError("500", "该用户已被禁用");
        }
        if (outsideUser.isEnabled() == true && enabled == true) {
            return JsonResponse.errorResponseWithError("500", "该用户已被激活");
        }
        outsideUser.setEnabled(enabled);
        userProfileRepository.save(outsideUser);
        User user = outsideUser.getUser();
        user.setEnabled(enabled);
        outsideUserRepository.save(user);
        Map<String, Object> data = new HashMap<>();
        data.put("str", outsideUser.getRealName());
        if (enabled) {
            userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_enable, LogConstants.business_type_system_user, null, data);
        } else {
            userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_freeze, LogConstants.business_type_system_user, null, data);
        }
        return JsonResponse.successResponse();
    }

    @ApiOperation("用户资料导出")
    @RequestMapping(value = "/userInfoExport", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse userInfoExport(HttpServletRequest request,
                                       @ApiParam("员工编号") @RequestParam(value = "code", required = false) String code,
                                       @ApiParam("姓名") @RequestParam(value = "name", required = false) String name,
                                       @ApiParam("手机号码") @RequestParam(value = "telephone", required = false) String telephone,
                                       @ApiParam("关联部门") @RequestParam(value = "departmentIds", required = false) Long departmentIds) {
        JsonResponse jsonResponse = userProfileService.userInfoExport(code, name, telephone, departmentIds);
        List<String[]> userInfoList = (List<String[]>) jsonResponse.getData();
        String templetPath = request.getSession().getServletContext().getRealPath("");
        String fileName = "用户资料导出.xlsx";
        String sheetName = "用户资料";
        XSSFWorkbook wb = getStationInfoExport(null, sheetName, userInfoList);
        try {
            FileOutputStream outputStream = new FileOutputStream(new File(templetPath + "/export/" + fileName));
            wb.write(outputStream);
            outputStream.close();
            String filePath = "http://vr.duluxdesigner.com.cn/export/" + fileName;
//            String filePath = "http://116.62.64.140:51002/export/" + fileName;

            try {
                Map<String, Object> searchParams = new HashMap<>();
                searchParams.put("员工编号", code);
                searchParams.put("姓名", name);
                searchParams.put("手机号码", telephone);
                searchParams.put("关联部门", departmentIds);
                String desc = "筛选了:";
                for (String key : searchParams.keySet()) {
                    if (null != searchParams.get(key) && !StringUtils.isEmpty(searchParams.get(key).toString())) {
                        desc += (key + "=>" + searchParams.get(key) + " ,");
                    }
                }
                if ("筛选了:".equals(desc)) {
                    desc = "";
                }
                Map<String, Object> data = new HashMap<>();
                data.put("str", desc);
                userLogService.addUserLog(this.getCurrentUser(), null,
                        LogConstants.operate_type_send_export,
                        LogConstants.business_type_system_user_detail, null, data);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return JsonResponse.successResponseWithData(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResponse.successResponse();
    }

    private static String[] userInfoTitle = {"编号", "姓名", "手机号", "部门类型", "所属部门", "所属省份", "汽车品牌", "选择维修站", "品牌定位", "功能权限", "状态"};

    private XSSFWorkbook getStationInfoExport(XSSFWorkbook workbook, String sheetName, List<String[]> userInfoList) {
        if (workbook == null) {
            workbook = new XSSFWorkbook();
        }
        XSSFSheet sheet = workbook.createSheet(sheetName);
        for (int i = 0; i < userInfoList.get(0).length; i++) {
            sheet.setColumnWidth(i, 20 * 2 * 256);
        }
        XSSFFont titleFont = workbook.createFont();
        titleFont.setFontName("微软雅黑");
        titleFont.setFontHeightInPoints((short) 10);
        titleFont.setColor(IndexedColors.WHITE.getIndex());
        titleFont.setBold(true);
        XSSFCellStyle titleStyle = workbook.createCellStyle();
        XSSFColor titleColor = new XSSFColor(new java.awt.Color(68, 114, 196));
        titleStyle.setFillForegroundColor(titleColor);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setFont(titleFont);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setLeftBorderColor(titleColor);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setRightBorderColor(titleColor);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setTopBorderColor(titleColor);

        XSSFColor myColor1 = new XSSFColor(new java.awt.Color(180, 198, 231));
        XSSFCellStyle titleStyle2 = workbook.createCellStyle();
        titleStyle2.setAlignment(HorizontalAlignment.CENTER);
        titleStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle2.setFillForegroundColor(myColor1);
        titleStyle2.setBorderTop(BorderStyle.THIN);
        titleStyle2.setBorderBottom(BorderStyle.THIN);
        titleStyle2.setBorderRight(BorderStyle.THIN);
        titleStyle2.setTopBorderColor(myColor1);
//        titleStyle2.setWrapText(true);
        XSSFFont font2 = workbook.createFont();
        font2.setFontName("微软雅黑");
        font2.setFontHeightInPoints((short) 10);
        titleStyle2.setFont(font2);


        XSSFCellStyle titleStyle3 = workbook.createCellStyle();
        titleStyle3.setAlignment(HorizontalAlignment.CENTER);
        titleStyle3.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle3.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle3.setFillForegroundColor(myColor1);
        titleStyle3.setBorderTop(BorderStyle.THIN);
        titleStyle3.setBorderBottom(BorderStyle.THIN);
        titleStyle3.setBorderRight(BorderStyle.NONE);
        titleStyle3.setTopBorderColor(myColor1);
        titleStyle3.setFont(font2);
//        titleStyle3.setWrapText(true);

        XSSFColor myColor2 = new XSSFColor(new java.awt.Color(217, 225, 242));
        XSSFCellStyle titleStyle4 = workbook.createCellStyle();
        titleStyle4.setAlignment(HorizontalAlignment.CENTER);
        titleStyle4.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle4.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle4.setFillForegroundColor(myColor2);
        titleStyle4.setBorderTop(BorderStyle.THIN);
        titleStyle4.setBorderBottom(BorderStyle.THIN);
        titleStyle4.setBorderRight(BorderStyle.NONE);
        titleStyle4.setTopBorderColor(myColor2);
        titleStyle4.setFont(font2);
//        titleStyle4.setWrapText(true);

        XSSFCellStyle titleStyle5 = workbook.createCellStyle();
        titleStyle5.setAlignment(HorizontalAlignment.CENTER);
        titleStyle5.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle5.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle5.setFillForegroundColor(myColor2);
        titleStyle5.setBorderTop(BorderStyle.THIN);
        titleStyle5.setBorderBottom(BorderStyle.THIN);
        titleStyle5.setBorderRight(BorderStyle.THIN);
        titleStyle5.setTopBorderColor(myColor2);
        titleStyle5.setFont(font2);
//        titleStyle5.setWrapText(true);

        XSSFRow row1 = sheet.createRow(0);
        XSSFCell cell1 = null;
        //创建标题
        for (int i = 0; i < userInfoTitle.length; i++) {
            cell1 = row1.createCell(i);
            cell1.setCellValue(userInfoTitle[i]);
            cell1.setCellStyle(titleStyle);
        }
        XSSFCell sheet1Cell2 = null;
        for (int i = 0; i < userInfoList.size(); i++) {
            row1 = sheet.createRow(i + 1);
            for (int j = 0; j < userInfoList.get(i).length; j++) {
                sheet1Cell2 = row1.createCell(j);
                //将内容按顺序赋给对应的列对象
                if (j == userInfoList.get(i).length - 1) {
                    if (i % 2 == 0) {
                        sheet1Cell2.setCellStyle(titleStyle2);
                    } else {
                        sheet1Cell2.setCellStyle(titleStyle5);
                    }
                    try {
                        sheet1Cell2.setCellValue(Long.valueOf(userInfoList.get(i)[j]));
                    } catch (Exception e) {
                        sheet1Cell2.setCellValue(userInfoList.get(i)[j]);
                    }

                } else {
                    if (i % 2 == 0) {
                        sheet1Cell2.setCellStyle(titleStyle3);
                    } else {
                        sheet1Cell2.setCellStyle(titleStyle4);
                    }
                    try {
                        sheet1Cell2.setCellValue(Long.valueOf(userInfoList.get(i)[j]));
                    } catch (Exception e) {
                        sheet1Cell2.setCellValue(userInfoList.get(i)[j]);
                    }
                }
            }
        }
        return workbook;
    }

}
